from datetime import datetime
from random import randint
import simplejson

from django.shortcuts import render
from django.db.models import Count, Max, Min, Sum, Avg
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from django.core import serializers
from .models import Category, SalesCell, Order, OrderDetails


# Create your views here
def generate_order_number():
    dt = datetime.now()
    return "{}{:0>2d}{:0>2d}{:0>2d}{:0>2d}{:0>2d}{}".format(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                                                            randint(1000, 9999))


def index(request):
    return HttpResponse("Hello world!")


@csrf_exempt
def sales_cell(request):
    if request.method == "POST":
        post_json = simplejson.loads(request.body)
        seat = post_json["seat"]
        orders = post_json["orders"]

        order_number = generate_order_number()
        order = Order(seat=seat, order_number=order_number, status=1)
        order.save()
        for item in orders:
            order_detail = OrderDetails(order=order, sales_cell=SalesCell.objects.get(pk=item["id"]), nums=item["nums"])
            order_detail.save()
        return HttpResponse("OK!")
    else:
        # return HttpResponse(serializers.serialize("json", SalesCell.objects.all()))
        category_list = [category.to_dict(expand=True) for category in Category.objects.all()]
        return JsonResponse(category_list, safe=False)


@csrf_exempt
def chef(request):
    if request.method == "POST":
        post_json = simplejson.loads(request.body)
        sales_cell_id = post_json["sales_cell_id"]
        nums = post_json["nums"]
        order_details = OrderDetails.objects.all().filter(sales_cell_id=sales_cell_id).exclude(status=3).order_by(
            "order__created_time")
        order_set = set()
        for order_detail in order_details:
            remain_nums = order_detail.nums - order_detail.completed_nums
            if nums >= remain_nums:
                nums -= remain_nums

                order_detail.completed_nums = order_detail.nums
                order_detail.status = 3
                order_set.add(order_detail.order)
            else:
                order_detail.completed_nums += nums
                order_detail.status = 2
                nums = 0

            order_detail.save()

            if nums == 0:
                break

        for order in order_set:
            order_details = OrderDetails.objects.filter(order=order).exclude(status=3)
            if order_details.count() == 0:
                order.status = 3
                order.save()

        return HttpResponse("OK!")
    else:
        order_details = OrderDetails.objects.exclude(status=3).values("sales_cell_id", "sales_cell__name").annotate(
            total=Sum("nums"),
            earliest_order_time=Min(
                "order__created_time")).order_by(
            "earliest_order_time")
        return JsonResponse(list(order_details), safe=False)
